package com.thirtydays.frame.base.http.error

import com.google.gson.JsonParseException
import com.thirtydays.frame.R
import com.thirtydays.frame.base.bean.BaseBean
import com.thirtydays.frame.util.ext.gToBean
import com.thirtydays.frame.util.ext.getCompatString
import com.thirtydays.frame.util.ext.isNull
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import javax.net.ssl.SSLHandshakeException

/**
 * @创建者：小垚
 * @时间：2021/7/22
 * @描述：
 */
class ExceptionHandle {
    companion object {
        fun handleException(throws: Throwable): String {
            when (throws) {
                is SocketTimeoutException -> return getCompatString(R.string.http_error_socket)

                is ConnectException       -> return getCompatString(R.string.http_error_connect)

                is HttpException          -> {
                    return when (throws.code()) {
                        504  -> getCompatString(R.string.http_error_504)
                        404  -> getCompatString(R.string.http_error_404)
                        401  -> getCompatString(R.string.http_error_401)
                        else -> if (throws.response().isNull()) {
                            getCompatString(R.string.http_error_request)
                        } else {
                            val errorBody = throws.response()!!.errorBody()
                            if (errorBody.isNull()) {
                                getCompatString(R.string.http_error_request)
                            } else {
                                val gToBean = errorBody!!.string().gToBean<BaseBean<*>>()
                                if (gToBean.isNull()) {
                                    getCompatString(R.string.http_error_request)
                                } else {
                                    gToBean!!.errorMessage
                                }
                            }
                        }
                    }
                }
                is UnknownHostException   -> return getCompatString(R.string.http_error_unkonown)

                is JsonParseException     -> return getCompatString(R.string.http_error_json)

                is SSLHandshakeException  -> return getCompatString(R.string.http_error_ssl)

                is ApiException           -> return if (throws.message == null) "" else throws.message!!
            }

            return getCompatString(R.string.http_error_retun)
        }
    }
}